package 面试真题;

import java.util.Arrays;
import java.util.Scanner;

public class Ali404 {
    private static int ans = 1 << 30;
    private static int n;
    private static int m;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        m = scanner.nextInt();
        char[][] chars = new char[n][m];
        scanner.nextLine();
        int start = 0, start2 = 0;
        for (int i = 0; i < n; i++) {
            String s = scanner.nextLine();
            chars[i] = s.toCharArray();
            for (int j = 0; j < chars.length; j++) {
                if (chars[i][j] == 'S') {
                    start = i;
                    start2 = j;
                    break;
                }
            }
        }
        traceBack(start, start2, new boolean[n][m], 5, chars, 0);
        System.out.println(ans);
    }

    private static void traceBack(int i, int j, boolean[][] visited, int leveTimes, char[][] values, int time) {
        if (visited[i][j] || values[i][j] == '#') return;
        visited[i][j] = true;
        if (values[i][j] == 'E') {
            ans = Math.min(ans, time);
        }
        if (leveTimes > 0 && n - 1 - i >= 0 && n - 1 - i < n && m - 1 - j >= 0 && m - 1 - j < m) {
            traceBack(n - 1 - i, m - 1 - j, visited, leveTimes - 1, values, time + 1);
        }
        if (i > 0) traceBack(i - 1, j, visited, leveTimes, values, time + 1);
        if (i < n - 1) traceBack(i + 1, j, visited, leveTimes, values, time + 1);
        if (j > 0) traceBack(i, j - 1, visited, leveTimes, values, time + 1);
        if (j < m - 1) traceBack(i, j + 1, visited, leveTimes, values, time + 1);
        visited[i][j] = false;
    }
}
